import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { successResponse, errorResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const body = await req.json();
  // 兼容 page 与 current 两种分页参数命名
  const page = Number(body.page ?? body.current ?? 1);
  const pageSize = Number(body.pageSize ?? 10);
  const title = body.title;
  const typeRaw = body.type;
  const isBannerRaw = body.isBanner;

  const where: any = {};
  if (title) {
    where.title = {
      contains: title,
    };
  }
  if (typeRaw !== undefined && typeRaw !== null) {
    const typeNum = typeof typeRaw === 'string' ? parseInt(typeRaw, 10) : typeRaw;
    if (!Number.isNaN(typeNum)) {
      where.type = typeNum;
    }
  }
  if (isBannerRaw !== undefined && isBannerRaw !== null) {
    const bannerNum = typeof isBannerRaw === 'string' ? parseInt(isBannerRaw, 10) : isBannerRaw;
    if (!Number.isNaN(bannerNum)) {
      where.isBanner = bannerNum;
    }
  }

  const [total, contents] = await prisma.$transaction([
    prisma.content.count({ where }),
    prisma.content.findMany({
      where,
      skip: (page - 1) * pageSize,
      take: pageSize,
      include: {
        categories: {
          include: {
            category: true,
          },
        },
        cover: true,
      },
    }),
  ]);

  const totalPages = Math.ceil(total / pageSize);

  return successResponse({
    data: contents.map((content) => ({
      ...content,
      categories: content.categories.map((c) => c.category),
      cover: content.cover
        ? {
            ...content.cover,
            createdAt: content.cover.createdAt.toISOString(),
          }
        : null,
    })),
    total,
    pageSize,
    page, // 统一返回 page 字段
    current: page, // 保留兼容字段，避免旧前端代码出错
    totalPages,
  });
}

export const POST = withMiddleware(handler);